
import to_page from '../../../commons/pageaddress.js'
var requests = require('../../../requests/api.js');
import util from '../../../utils/util.js'
var pay = require('../../../requests/pay.js');
// 定义一个总毫秒数，以一分钟为例。TODO，传入一个时间点，转换成总毫秒数
var total_micro_second = 10 * 1000;
let app = getApp()
Page({
  ///
  /**
   * 页面的初始数据
   */
  data: {
    shopText: '商品清单',
    clock: '',
    timer: '',
    orderCode: '',
    isList: false,// 是否从订单页面进来
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    new app.WeToast();
    const that = this
    that.data.orderCode = options.orderCode;

    that.data.isList = options.isList;
    // wx.showLoading({
    //   title: '',
    // })
  },
  refresh_UI: function (orderStatus) {
    const that = this;
    switch (orderStatus) { // 如果为第二个说明为点击地址栏 弹出选择器框
      case 2:
        //  this.risePicker()
        that.data.shopText = '未发货商品清单'
        break
      default:
        break
    }
    that.setData({
      shopText: that.data.shopText
    })
  },
  //请求网络 -- 获取订单详情
  request_order_detail: function () {
    const that = this;

    requests.get_orderDetail(that.data.orderCode, (res) => {
      that.setData(
        res.data
      )
      total_micro_second = res.data.leftPaySeconds;
      that.setData({
        clock: that.date_format(total_micro_second)
      });
      that.refresh_UI(res.data.orderStatus);
    }, (data) => {
      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }
    }, () => {
      wx.stopPullDownRefresh()
      if (total_micro_second > 0) {
        that.count_down();
      }
    });
  },
  //请求网络 -- 取消订单
  request_delete_order: function () {
    const that = this;
    wx.showLoading({
      title: '',
    })
    requests.delete_order(that.data.orderCode, (res) => {
      that.request_order_detail();
      that.refresh_orderList()
    }, (data) => { 
      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }
    }, () => { });
  },
  //请求网络 -- 用户确认收货
  request_put_order: function () {
    const that = this;
    wx.showLoading({
      title: '',
    })
    requests.put_order(that.data.orderCode, (res) => {
      that.request_order_detail();
      that.refresh_orderList()

    }, (data) => {
      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }
     }, () => { });
  },
  // 取消订单
  delete_order: function () {
    const t = this;
    wx.showModal({
      title: '提示',
      content: '确定取消订单吗？',
      success: function (res) {
        if (res.confirm) { // 点击确定
          t.request_delete_order()
          wx.reportAnalytics('order_cancle_button', {
          });
        }
      }
    })
  },
  // 支付 or 用户确认收货
  pay_Action: function (e) {
    const t = this;
    var $mold = e.currentTarget.dataset.mold;
    if ($mold == 'pay') {
      t.wx_pay();
    } else if ($mold == 'sure') {
      wx.showModal({
        title: '提示',
        content: '确定收货吗？',
        success: function (res) {
          if (res.confirm) { // 点击确定
            t.request_put_order()
          }
        }
      })
    }
  },
  //微信支付按钮
  wx_pay: function () {
    const that = this;
    wx.showLoading({
      title: '',
    })
    ///微信支付的时候先拿缓存。看是否有openId
    wx.getStorage({
      key: 'openId',
      success: function (res) {
        if (res.data) {
          var params = {
            openId: res.data,
            orderNo: that.data.orderCode,
            channel: "wx_lite",
            clientIp: "127.0.0.1"
          };
          that.getcharge(params)
        } else {
          //调用登录接口
          wx.login({
            success: (ev) => {
              var code = ev.code
              that.code2Session(code)
            }
          })
        }
      },
      fail: function (res) {
        console.log('s:获取失败openId缓存失败')
        //调用登录接口
        wx.login({
          success: (ev) => {
            var code = ev.code
            that.code2Session(code)
          }
        })
      }
    })

  },

  code2Session: function (code) {
    var params = {
      code: code
    }
    requests.post_code2Session(params, (res) => {
      if (res.data) {
        wx.setStorage({
          key: 'openId',
          data: res.data.openId
        })
        var params = {
          openId: res.data.openId,
          orderNo: this.data.orderCode,
          channel: "wx_lite",
          clientIp: "127.0.0.1"
        };
        this.getcharge(params)
      }
    }, () => {

    }, () => {

    });
  },
  getcharge: function (params) {
    pay.request_charge(params, (res) => {
      wx.hideLoading()
      wx.reportAnalytics('pay_wechat_success', {
        price: this.data.orderAmount,
        ordercode: this.data.orderCode
      })
      that.request_order_detail()
      that.refresh_orderList()
    }, (res) => {
      wx.hideLoading()
    });
  },
  // 刷新订单列表页数据
  refresh_orderList: function () {
    if (!this.data.isList) {
      return;
    }
    var pages = getCurrentPages() // 获取当前栈里面页面
    var prevPage = pages[pages.length - 2]  //上一个页面
    prevPage.refresh_current_data()
  },
  /* 毫秒级倒计时 */
  count_down: function () {
    const that = this;
    var time1 = that.data.timer
    time1 = setInterval(function () {
      // 渲染倒计时时钟
      total_micro_second -= 1;
      if (total_micro_second <= 0) {
        that.setData(
          that.data
        )
        that.setData({
          clock: ""
        });
        // timeout则跳出并结束递归
        clearInterval(time1);
        return;
      }
      that.setData({
        timer: time1,
        clock: that.date_format(total_micro_second)
      });
    }, 1000)
  },

  // 时间格式化输出,每10ms都会调用一次
  date_format: function (micro_second) {
    // 秒数
    var second = Math.floor(micro_second);
    // 小时位
    var hr = this.fill_zero_prefix(Math.floor(second / 3600));
    // 分钟位
    var min = this.fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
    // 秒位
    var sec = this.fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
    if (hr == "00") {
      if (min == "00") {
        return sec + "秒";
      }else {
        return min + "分钟";

      }
      
    } else {
      return hr + "小时" + min + "分钟";
    }
  },

  // 位数不足补零
  fill_zero_prefix: function (num) {
    return num < 10 ? "0" + num : num
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this
    that.request_order_detail()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    clearInterval(this.data.timer);
    this.request_order_detail()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 拨打客服电话
   */
  callService: function () {
    var csPhone = wx.getStorageSync('csPhone')
    wx.makePhoneCall({
      phoneNumber: csPhone,
    })
  },
  goods_detailClick: function (e) {

    var id = e.currentTarget.dataset.productid;
    var url = to_page.t + to_page.goGoodsDetail + id;
    to_page.to(url)

  },
  // 超过三件商品时  显示为可点击向下 展示所有商品
  collapse: function (ev) {
    this.setData({
      notCollapse: !this.data.notCollapse,
    })
  }

})

